package com.bestvike.stone.spring.shiro.annotation.handler;

import com.bestvike.stone.spring.shiro.SecurityUtils;
import com.bestvike.stone.spring.shiro.annotation.RequiresPermissions;
import com.bestvike.stone.spring.shiro.authz.exception.AuthorizationException;
import com.bestvike.stone.spring.shiro.authz.exception.authz.UnauthorizedException;

import java.lang.annotation.Annotation;

/**
 * 权限注解处理器
 */
public final class PermissionAnnotationHandler implements AuthorizingAnnotationHandler {
    /**
     * 获取支持的注解类型
     */
    @Override
    public Class<? extends Annotation> getAnnotationClass() {
        return RequiresPermissions.class;
    }

    /**
     * 断言权限
     */
    @Override
    public void assertAuthorized(Annotation annotation) throws AuthorizationException {
        RequiresPermissions requiresPermissions = (RequiresPermissions) annotation;
        final String[] permissions = requiresPermissions.value();
        if (permissions.length == 0)
            throw new UnauthorizedException("no permissions set for RequiresPermissions");
        switch (requiresPermissions.logical()) {
            case AND:
                final boolean hasAllPermission = SecurityUtils.hasAllPermission(permissions);
                if (!hasAllPermission)
                    throw new UnauthorizedException();
                break;
            case OR:
                final boolean hasAnyPermission = SecurityUtils.hasAnyPermission(permissions);
                if (!hasAnyPermission)
                    throw new UnauthorizedException();
            default:
                break;
        }
    }
}
